import socket
import threading
import json


class Server:
    def __init__(self, host='0.0.0.0', port=12345):
        self.host = host
        self.port = port
        self.server_socket = None
        self.clients = []
        self.running = False

    def start(self):
        """启动服务器"""
        self.running = True
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_socket.bind((self.host, self.port))
        self.server_socket.listen(5)
        print(f"服务器启动，监听 {self.host}:{self.port}")

        # 启动接受客户端连接的线程
        threading.Thread(target=self.accept_clients, daemon=True).start()

    def accept_clients(self):
        """接受客户端连接"""
        while self.running:
            try:
                client_socket, addr = self.server_socket.accept()
                print(f"新连接: {addr}")
                self.clients.append(client_socket)

                # 为每个客户端启动处理线程
                threading.Thread(
                    target=self.handle_client,
                    args=(client_socket, addr),
                    daemon=True
                ).start()
            except Exception as e:
                if self.running:
                    print(f"接受连接错误: {e}")

    def handle_client(self, client_socket, addr):
        """处理客户端消息"""
        try:
            while self.running:
                data = client_socket.recv(4096).decode('utf-8')
                if not data:
                    break

                # 解析JSON数据
                try:
                    json_data = json.loads(data)
                    print(f"来自 {addr} 的数据: {json_data}")

                    # 这里可以添加处理逻辑
                    response = {"status": "success", "message": "数据已接收"}
                    client_socket.sendall(json.dumps(response).encode('utf-8'))
                except json.JSONDecodeError:
                    error_msg = {"status": "error", "message": "无效的JSON格式"}
                    client_socket.sendall(json.dumps(error_msg).encode('utf-8'))
        except Exception as e:
            print(f"处理客户端 {addr} 错误: {e}")
        finally:
            print(f"客户端 {addr} 断开连接")
            if client_socket in self.clients:
                self.clients.remove(client_socket)
            client_socket.close()

    def stop(self):
        """停止服务器"""
        self.running = False
        if self.server_socket:
            self.server_socket.close()

        # 关闭所有客户端连接
        for client in self.clients:
            client.close()
        self.clients = []
        print("服务器已停止")


if __name__ == "__main__":
    server = Server()
    try:
        server.start()
        while True:
            cmd = input("输入 'stop' 停止服务器: ")
            if cmd.lower() == 'stop':
                break
    finally:
        server.stop()